﻿using MediatR;
using PublicClass;
using S.Produce.Domains;
using S.Produce.Infrastructure;
using S.Produce.Read.Api.Application.Commands.HistoryCommands;

namespace S.Produce.Read.Api.Application.CommandHandlers.HistoryCommandHandlers
{
    public class HistorySelectCommandHandler : IRequestHandler<HistorySelectCommand, PageInfo<History>>
    {
        private readonly IRepository<History> _repository;

        public HistorySelectCommandHandler(IRepository<History> repository)
        {
            _repository = repository;
        }

        public async Task<PageInfo<History>> Handle(HistorySelectCommand request, CancellationToken cancellationToken)
        {
            var info = await _repository.GetAllAsync();
            var res = info.AsQueryable().Where(x => x.IsDel == false);
            if (!string.IsNullOrEmpty(request.InDate))
            {
                var sdate = request.InDate.Split(",")[0];
                var edate = request.InDate.Split(",")[1];
                res = res.Where(x => x.BreedingDate >= DateTime.Parse(sdate) && x.BreedingDate <= DateTime.Parse(edate));
            }
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                res = res.Where(x => x.Earbugles == request.Earbugles);
            }
            int totalCount = res.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            res = res.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            return new PageInfo<History>
            {
                datas = res.ToList(),
                pageCount = pageCount,
                totalCount = totalCount,
            };
        }
    }
}
